package com.zut.utils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zut.mapper.ManagerMapper;
import com.zut.pojo.Manager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @author: Mr.Liu
 * @create: 2021-11-16 12:42
 */
@Component
public class UserUtil {

    @Value("${jwt.tokenHeader}")// tokenHeader: Authorization
    String tokenHeader;
    @Value("${jwt.tokenHead}")
    String tokenHead;//  tokenHead: Bearer

    @Autowired
    JwtTokenUtil jwtTokenUtil;

    @Autowired
    ManagerMapper managerMapper;

    public Integer getUserId(HttpServletRequest request) {
        String authHeader = request.getHeader(this.tokenHeader);
        if (null != authHeader && authHeader.startsWith(this.tokenHead)) {
            String authToken = authHeader.substring(this.tokenHead.length());
            String username = jwtTokenUtil.getUserNameFormToken(authToken);
            Manager manager = managerMapper.selectOne(new QueryWrapper<Manager>().eq("username", username));
            return manager.getId();
        }
        return null;
    }

    public Manager getManager(HttpServletRequest request) {
        String authHeader = request.getHeader(this.tokenHeader);
        if (null != authHeader && authHeader.startsWith(this.tokenHead)) {
            String authToken = authHeader.substring(this.tokenHead.length());
            String username = jwtTokenUtil.getUserNameFormToken(authToken);
            return managerMapper.selectOne(new QueryWrapper<Manager>().eq("username", username));
        }
        return null;
    }
}
